﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using DapperExtensions;
using ExaminationSys.DataAccess.Entity;
using SQLinq;
using SQLinq.Dapper;

namespace ExaminationSys.DataAccess.Repository
{
    public class DBAnswerRepository : Repository<DBAnswer>
    {
        public DBAnswerRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }
        private SqlConnection db;
        public override DBAnswer GetById(dynamic id)
        {            
            return base.ObjectSet.Get<DBAnswer>(db, id, null, null);
        }
    }

    public class DBAnswerService
    {
        private DBAnswerService()
        {
        }

        public DBAnswer Get(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBAnswer.GetById(id);
                return result;

            }
        }

        public bool ChecQuesIDAndPrefix(string questiondi, string prefix)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<DBAnswer>(f => f.DBQuestionID, Operator.Eq, questiondi));
                pg.Predicates.Add(Predicates.Field<DBAnswer>(f => f.Prefix, Operator.Eq, prefix));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBAnswer.GetList(pg).FirstOrDefault();
                return result != null;
            }
        }

        public List<DBAnswer> GetAll()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBAnswer.GetList();
                return result.ToList();
            }
        }

        public List<DBAnswer> GetAll(Guid questionid)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<DBAnswer>(f => f.DBQuestionID, Operator.Eq, questionid));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBAnswer.GetList(pg);

                return result.ToList<DBAnswer>();
            }
        }

        public bool Delete(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"delete from DBAnswer where ID=@TmpId",
                                         new[] { new { TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Lock(List<string> ids, int _lock)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update DBAnswer set Lock=@lk where ID=@TmpId",
                                         new[] { new { lk = _lock, TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Update(DBAnswer entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.DBAnswer.Update(entity);
            }
        }
        public dynamic Insert(DBAnswer entity)
        {
            bool exitst = ChecQuesIDAndPrefix(entity.DBQuestionID.ToString(), entity.Prefix);
            if (exitst)
                return Update(entity);
            else
            {
                using (var db = DataContent.DBServer())
                {
                    IUnitOfWork work = new UnitOfWork(db);
                    return work.DBAnswer.Insert(entity, null);
                }
            }
        }

        public List<DBAnswer> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "DBAnswer",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<DBAnswer>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }

        public List<DBAnswer> GetQuestionAnswer(string questionid)
        {
            if (string.IsNullOrWhiteSpace(questionid))
                return null;

            using (var db = DataContent.DBServer())
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("select * from DBAnswer where ");
                sb.AppendFormat(" DBQuestionID='{0}'",questionid);
                sb.Append(" order by Prefix");
                var items = db.Query<DBAnswer>(sb.ToString());
                return items.ToList();
            }
        }

        public void DeleteRepeateDBAnswer()
        {
            int totalPage, totalRecord;
            List<DBAnswer> list = GetListByPage("", "DBQuestionID,Prefix", 10000, 1, out totalPage, out totalRecord);
            string tempid = string.Empty, tempprefix = string.Empty;
            List<string> listid = new List<string>();
            if (list != null && list.Count > 1)
            {
                int count = list.Count;
                tempprefix = list[0].Prefix;
                tempid = list[0].DBQuestionID.ToString();
                for (int i = 1; i < count; i++)
                {
                    if (tempid.Equals(list[i].DBQuestionID.ToString())
                        && tempprefix.Equals(list[i].Prefix))
                        listid.Add(list[i].ID.ToString());
                    else
                    { tempid = list[i].DBQuestionID.ToString(); tempprefix = list[i].Prefix; }
                }
                if (listid != null && listid.Count > 0)
                    Delete(listid);
            }
        }
    }    
}
